package org.hot100_3;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class leetcode102 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        return BFS(root);
    }

    public List<List<Integer>> BFS(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root==null){
            return res;
        }

        Deque<TreeNode> deque = new ArrayDeque<>();

        deque.add(root);

        while (!deque.isEmpty()) {
            int size = deque.size();
            List<Integer> item = new ArrayList<>();
            while (size > 0) {
                TreeNode node = deque.pop();
                item.add(node.val);

                if (node.left != null) {
                    deque.offer(node.left);
                }

                if (node.right != null) {
                    deque.offer(node.right);
                }
                size--;
            }
            res.add(item);
        }

        return res;
    }
}
